package com.heima.user.service.impl;

import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import com.heima.user.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private CacheService cacheService;

    /**
     * 用户关注与取消
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        Integer userId = user.getId();
        if (userId == null || userId == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        Integer authorId = dto.getAuthorId();
        Short operation = dto.getOperation();

        // 关注
        if (0 == operation) {
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId.toString(), System.currentTimeMillis());
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION + authorId, userId.toString(), System.currentTimeMillis());
        }
        // 取消关注
        else if (1 == operation) {
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId.toString());
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + authorId, userId.toString());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}